package com.itcoon.cloud.framework.webmvc.exception.handler;

import com.itcoon.cloud.framework.ex.errorcode.CommonServiceErrorCode;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;
import com.itcoon.cloud.framework.webmvc.config.properties.GlobalWebConfigProperties;
import org.springframework.validation.BindException;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class BindExceptionHandler extends ParamsExceptionHandler<BindException> {

    private final GlobalWebConfigProperties properties;

    public BindExceptionHandler(GlobalWebConfigProperties properties) {
        this.properties = properties;
    }

    @Override
    public boolean support(Exception e) {
        return e instanceof BindException;
    }

    @Override
    public void handle(HttpServletResponse response, BindException e) {
        loopLog(e);
        List<String> parameterExceptionMessages = doParamsEx(e.getFieldErrors(), e.getTarget());
        ApiResponseUtils.writeJsonResponse(response, ApiResponse.error(CommonServiceErrorCode.BAD_PARAMETER.getCode(), CommonServiceErrorCode.BAD_PARAMETER.getMessage(), parameterExceptionMessages), properties.getResponse().getBizExceptionHttpStatus().value());
    }
}
